import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

//import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_module/event/SwitchMode1_4Event.dart';
import 'package:flutter_module/event/connect_mqtt_event.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:flutter_module/beans/Entity.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/commom/data/const.dart';
import 'package:flutter_module/event/ProductContentEvent.dart';
import 'package:flutter_module/event/getSetting_event.dart';
import 'package:oktoast/oktoast.dart';
import 'package:typed_data/typed_buffers.dart';
import 'dart:async';
import 'dart:io';

class Mqtt {
  String server = "tcp://119.45.49.242";
  int port = 1883;
  String clientIdentifier = "my dart exp";
  static String subTopic = "";
  static String publishTopic = "";
  static String App_UUID = "";
  MqttQos qos = MqttQos.atLeastOnce;
  MqttClient mqttClient;
  static Mqtt _instance;
  Data currentDeviceAllDatas;

  List<double> _showsliderValue = [0.0, 0.0, 0.0, 0.0];

  List<double> _sliderValues1 = [8.0, 5.0, 8.0, 5.0];
  List<double> _sliderValues2 = [8.0, 5.0, 8.0, 5.0];
  List<double> _sliderValues3 = [2.0, 2.0, 2.0, 3.0, 1.8];
  List<double> _sliderValues4 = [100.0, 50.0, 100.0, 50.0];

  //getPopWindow(context,true,0) 用最后一个参数来获取弹出内容
  List<String> singleTitle1 = [
    '快速度开门1时间',
    '慢速度开门1时间',
    '快速度关门1时间',
    '慢速度关门1时间'
  ]; //对应一个选项item = title+value
  List<String> singleTitle2 = ['快速度开门2时间', '慢速度开门2时间', '快速度关门2时间', '慢速度关门2时间'];
  List<String> singleTitle3 = ['关门延时时间', '开延时', '关延时', '遇阻回弹力', '停门检测力'];
  List<String> singleTitle4 = ['快开速度', '慢开速度', '快关速度', '慢关速度'];

  List<double> _sliderValues5 = [5.0, 5.0, 3.0];
  List<double> _sliderValues6 = [3.0, 1.8, 3.0, 1.8];
  List<String> doubleTitle1 = ['开门刹车距离', '关门刹车距离', '半开距离'];
  List<String> doubleTitle2 = ['快开门力', '慢开门力', '快关门力', '慢关门力'];
  List<Item> singleArgs = [];
  List<Item> doubleArgs = [];

  /// dart  生成固定随机数
  String getRandom() {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    int strlenght = 6;

    /// 生成的字符串固定长度
    String left = '';
    for (var i = 0; i < strlenght; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    print(left);
    return left;
  }

  Mqtt._() {
    mqttClient = MqttClient('119.45.49.242', App_UUID + getRandom());
//    mqttClient = MqttClient.withPort(server, clientIdentifier, port);
    ///连接成功回调
    mqttClient.onConnected = _onConnected;

    ///连接断开回调
//    mqttClient.onDisconnected = _onDisconnected;
    ///订阅成功回调
    mqttClient.onSubscribed = _onSubscribed;

    ///订阅失败回调
    mqttClient.onSubscribeFail = _onSubscribeFail;
  }

  static bool setInstance(App_esp_ip model) {
    subTopic = model.subscribe;
    publishTopic = model.subscribe;
    App_UUID = model.appUuid;
    if (_instance == null) {
      _instance = Mqtt._();
    }
    return true;
  }

  static Mqtt getInstance() {
    if (_instance == null) {
      _instance = Mqtt._();
    }
    return _instance;
  }

  ///连接
  connect() {
    mqttClient.connect();

    _log("connecting");
  }

  ///断开连接
  disconnect() {
    mqttClient.disconnect();
    _log("disconnect");
  }

  ///发布消息
  publishMessage(MqttClientPayloadBuilder builder) {
    //断开即提示和返回
    ///检查连接结果
    print(builder.payload);
    if (mqttClient.connectionStatus.state == MqttConnectionState.connected) {
//      print('EXAMPLE::Mosquitto client connected');
    } else {
        print('EXAMPLE::ERROR  - disconnecting, status is ${mqttClient.connectionStatus}');
        mqttClient.connect();
        // showToast("Mqtt client connection failed");
        showToast("远程连接超时，请稍后重试");
        return;
    }

    mqttClient.publishMessage(publishTopic, qos, builder.payload);
  }

  ///发布消息
  publishMessageWithResponse(
      MqttClientPayloadBuilder builder, Function callback) {
    //断开即提示和返回
    ///检查连接结果
    print(builder.payload);
    if (mqttClient.connectionStatus.state == MqttConnectionState.connected) {
      print('EXAMPLE::Mosquitto client connected');
    }else if(mqttClient.connectionStatus.state == MqttConnectionState.connecting){
        callback("connecting");
    } else {
      mqttClient.connect();
      print(
          'EXAMPLE::ERROR  - disconnecting, status is ${mqttClient.connectionStatus}');
          showToast("Mqtt connection failed");
          callback("time out");
          return;
    }

    mqttClient.publishMessage(publishTopic, qos, builder.payload);
  }

  ///消息监听
  _onData(List<MqttReceivedMessage<MqttMessage>> data) {
    final MqttPublishMessage recMess = data[0].payload;
    Uint8Buffer message = recMess.payload.message;
//    print(message);
    if (message.length < 6) {
      return;
    }
    if (message.elementAt(0) == 4 &&
        message.elementAt(1) == 4 &&
        message.elementAt(2) == 4 &&
        message.elementAt(3) == 4) {
      Application.eventBus.fire(new Switch1_4ModeEvent(message));
      return;
    }
    if (message.elementAt(0) == 229 &&
        message.elementAt(1) == 188 &&
        message.elementAt(2) == 128 &&
        message.elementAt(3) == 229) {
      Application.eventBus.fire(new ProductContentEvent('关到位'));
      return;
    }
    if (message.elementAt(0) == 229 &&
        message.elementAt(1) == 133 &&
        message.elementAt(2) == 179) {
      Application.eventBus.fire(new ProductContentEvent('开到位'));
      return;
    }
    if (message.elementAt(0) == 232 &&
        message.elementAt(1) == 191 &&
        message.elementAt(2) == 144 &&
        message.elementAt(3) == 232) {
      Application.eventBus.fire(new ProductContentEvent('运行中'));
      return;
    }

    if (message.length < 23) {
      return;
    }
    if (message.elementAt(0) == 72 && message.elementAt(1) == 2) {
      return;
    }
    List<double> itemValueDoubleValues2 = [];
    print(message.length);
    for (var i = 0; i < message.length; i++) {
      int intint = message.elementAt(i);
      itemValueDoubleValues2.add(intint.toDouble());
    }
    _sliderValues1 = itemValueDoubleValues2.sublist(0, 4);
    _sliderValues2 = itemValueDoubleValues2.sublist(4, 8);
    _sliderValues3 = itemValueDoubleValues2.sublist(8, 13);
    _sliderValues3[3] = _sliderValues3[3] / 10;
    _sliderValues3[4] = _sliderValues3[4] / 10;
    print("_sliderValues3 are:");
    print(_sliderValues3);
    _sliderValues4 = itemValueDoubleValues2.sublist(13, 17);
    _sliderValues5 = itemValueDoubleValues2.sublist(17, 20);
    _sliderValues6 = itemValueDoubleValues2.sublist(20, 24);

    singleArgs = [
      Item(_sliderValues1, singleTitle1),
      Item(_sliderValues2, singleTitle2),
      Item(_sliderValues3, singleTitle3),
      Item(_sliderValues4, singleTitle4),
      Item(_sliderValues5, doubleTitle1),
      Item(_sliderValues6, doubleTitle2)
    ];
    currentDeviceAllDatas = Data(singleArgs, doubleArgs);
    print(currentDeviceAllDatas);

    Application.eventBus.fire(new getSetting_event());

//    ByteBuffer byteBuffer = message.buffer;
//    int intint = message.elementAt(0);
    //byteBuffer.asInt32List();
//    Uint8List uint8buffer = Uint8List(32);
//    var messageStream = MqttByteBuffer(uint8buffer);
//    MqttReceivedMessage<MqttMessage> m = data.elementAt(0);
//    print(m.payload);
//    MqttMessage message = m.payload;
//    Uint8List binaryIntList = message.;
//    message.writeTo(messageStream);
//    //final MqttPublishMessage recMess = data[0].payload;
//    String messageTxt = Utf8Decoder().convert(uint8buffer);
    ///打印出来
    //print(uint8buffer.toString());
    //print(uint8buffer);
    ///服务器返回的数据信息
//    final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
//     print(pt);
//    Uint8Buffer uint8buffer = Uint8Buffer();
//    var messageStream = MqttByteBuffer(uint8buffer);

    // 第一种，就像 java 的 for 循环

//    print(itemValueDoubleValues2);
//    int count = 0;

//    print(singleArgs);
//    currentDeviceAllDatas= Data(singleArgs,doubleArgs);
//    print(currentDeviceAllDatas);
  }

  _onConnected() {
    _log("_onConnected");

    ///连接成功的时候订阅消息
    mqttClient.subscribe(subTopic, qos);
  }

  _onDisconnected() {
    _log("_onDisconnect");
    print('EXAMPLE::OnDisconnected client callback - Client disconnection');
    if (mqttClient.connectionStatus.returnCode ==
        MqttConnectReturnCode.solicited) {
      print('EXAMPLE::OnDisconnected callback is solicited, this is correct');
    }
    exit(-1);
  }

  _onSubscribed(String topic) {
    _log("_onSubscribed");

    ///在订阅成功的时候注册消息监听
    mqttClient.updates.listen(_onData);
    Application.eventBus.fire(new ConnectMqttEvent());
  }

  _onSubscribeFail(String topic) {
    _log("_onSubscribeFail");
  }

  _log(String msg) {
    print("MQTT-->$msg");
  }
}
